package com.f6.weixin.houtai.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.f6.exceptions.BusinessException;
import com.f6.service.CommonService;
import com.f6.utils.F6SystemUtils;
import com.f6.utils.F6WebUtil;
import com.f6.utils.SystemConstans;
import com.f6.vo.DBParameter;
import com.f6.weixin.common.vo.TextMessage;
import com.f6.weixin.common.vo.WeiXinOauth2Token;
import com.f6.weixin.common.vo.WeixinUserInfo;
import com.f6.weixin.services.MessageService;
import com.f6.weixin.utils.F6WXSessionUtil;
import com.f6.weixin.utils.MessageUtil;
import com.f6.weixin.utils.WeiXinUtils;
import com.f6.weixin.utils.WeixinAuthUtil;
import com.f6.weixin.vo.UserVO;

@Controller
public class WeiXinController {
	private Logger logger = LoggerFactory.getLogger(WeiXinController.class);

	@Autowired
	private MessageService messageservice;

	@Autowired
	private CommonService commonservice;

	@RequestMapping(value = "entrance", method = RequestMethod.POST, produces = "application/xml;charset=UTF-8")
	@ResponseBody
	public void entrance(HttpServletRequest request, HttpServletResponse response) throws BusinessException {
		logger.info("*****1*entrance***************************");

		// xml请求解析
		Map<String, String> requestMap;
		String responseMsg = "";
		try {
			requestMap = MessageUtil.parseXml(request);

			// 调用核心业务类接收消息、处理消息
			TextMessage textMessage = messageservice.processMessage(requestMap);
			String userOpenID = textMessage.getFromUserName();
			logger.info("--------------------Get user openid-----" + userOpenID);

			if (textMessage != null) {
				String eventType = textMessage.getEventType();
				String eventKey = textMessage.getEventKey();
				logger.info("eventType:" + eventType);
				logger.info("eventKey:" + eventKey);
				if ("VIEW".equals(eventType)) {
					// 点击开始点餐
					if (eventKey != null && eventKey.indexOf("prodlist.do")>0) {

						UserVO vo = getUserVOByOpenID(userOpenID);
						logger.info("Get user from DB:" + vo);
						// request.setAttribute("currentuser",userOpenID );
						if (vo != null) {
							logger.info("--------------------ddset user to session-----" + vo.toString());
							logger.info("--------------------ddset user to usercode-----" + vo.getUserCode());
							logger.info("--------------------ddset user to id-----" + vo.getIdCode());
							// F6WebUtil.setCurrentWeixinUser(request, vo);
							F6WXSessionUtil.getInstance().put(SystemConstans.SESSION_ATTR_USER + "_" + userOpenID, vo);

						} else {
							logger.info("--------------can not get user-----");
						}

					}
				}
				if (MessageUtil.EVENT_TYPE_SUBSCRIBE.equals(eventType)) {

					String weixintoken = getAccessToken(request);
					logger.info("userOpenID:" + userOpenID);
					logger.info("weixintoken:" + weixintoken);

					WeixinUserInfo weixinuser = WeiXinUtils.getUserDetail(weixintoken, userOpenID);

					if (weixinuser != null) {
						logger.info("===" + weixinuser.toString());

						try {
							String openid = weixinuser.getOpenId();
							if (!F6SystemUtils.isStrNull(openid)) {
								UserVO user = new UserVO();
								user.setIdCode(openid);
								user.setUserName(weixinuser.getNickname());

								Map paramap = F6SystemUtils.parseObj2Map(user);
								DBParameter dbparam = new DBParameter();
								dbparam.setAction("getUserByOpenID");
								dbparam.setModule("putong.User");
								dbparam.setParameter(paramap);
								Map resultmap = commonservice.queryOne(dbparam);
								// no user then do insert
								if (resultmap == null || resultmap.isEmpty()) {
									DBParameter dbinsertparam = new DBParameter();
									dbinsertparam.setAction("insert");
									dbinsertparam.setModule("putong.User");
									dbinsertparam.setParameter(paramap);
									Map map = commonservice.change(dbinsertparam, SystemConstans.CHANGE_ACTION_INSERT);
								}

							}

						} catch (BusinessException e) {
							logger.error("error when create user", e);
						}
						
					}
				}
			}

			// logger.info("===" + responseMsg);
			// 响应消息
			PrintWriter out = response.getWriter();
			response.setCharacterEncoding("utf-8");
			out.print(responseMsg);
			out.close();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@RequestMapping(value = "entrance", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String validateToken(HttpServletRequest request) {
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");
		if (WeiXinUtils.checkSignature(signature, timestamp, nonce)) {
			return echostr;
		}
		return "";
	}

	@RequestMapping(value = "accesstoken", method = RequestMethod.GET)
	@ResponseBody
	public String generateAccessToken(HttpServletRequest request) {
		String accesstoken = getAccessToken(request);
		return accesstoken;
	}

	@RequestMapping(value = "qrcode", method = RequestMethod.GET, produces = "application/text;charset=UTF-8")
	@ResponseBody
	public String generateQRCode(HttpServletRequest request) {

		String weixinToken = getAccessToken(request);

		String qrcode = "";
		String imageqrcode = "";
		String openId = "";

		String code = request.getParameter("code");
		logger.info("=====code=========" + code);
		// 用户同意授权
		if (!F6SystemUtils.isStrNull(code) && !"authdeny".equals(code)) {

			openId = getOpenID(code);

			// SNSUserInfo snsuserinfo = WeiXinUtils.getSNSUser(code,
			// accessToken, openId);
			// mv.addObject("snsUserInfo", snsuserinfo);
			// mv.setViewName("common/me");

			qrcode = WeiXinUtils.getPermQRCode(weixinToken, openId);

			// imageqrcode = "<img src=\"" + qrcode + "\"" + ">";
		} else {
			qrcode = WeiXinUtils.getTempQRCode(weixinToken, "");
			// imageqrcode = "<img src=\"" + qrcode + "\"" + ">";
			// imageqrcode = WeiXinUtils.utf8str("获取二维码失败");
		}
		imageqrcode = qrcode;
		logger.info("=====imageqrcode:" + imageqrcode);
		ModelAndView mv = new ModelAndView();
		mv.addObject("qrcode", imageqrcode);
		mv.setViewName("qt/qrcode");
		return imageqrcode;
	}

	private String getOpenID(String code) {
		String openId;
		WeiXinOauth2Token weixinOauth2Token = WeixinAuthUtil.getOauth2AccessToken(SystemConstans.APPID, SystemConstans.APPSECRET, code);
		String accessToken = weixinOauth2Token.getAccessToken();
		openId = weixinOauth2Token.getOpenId();
		logger.info("=====accessToken:" + accessToken);
		logger.info("=====openId:" + openId);
		return openId;
	}

	private String getAccessToken(HttpServletRequest request) {
		String accesstoken = (String) request.getSession().getAttribute(SystemConstans.WEIXIN_ACCESS_TOKEN);
		if (F6SystemUtils.isStrNull(accesstoken)) {
			accesstoken = WeiXinUtils.refreshAccessToken(request, SystemConstans.APPID, SystemConstans.APPSECRET);
			request.getSession().setAttribute(SystemConstans.WEIXIN_ACCESS_TOKEN, accesstoken);
		}
		return accesstoken;
	}

	@RequestMapping(value = "mydetails", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public WeixinUserInfo getUserDetails(HttpServletRequest request) {
		String code = request.getParameter("code");
		logger.info("=====code=========" + code);
		String weixintoken = getAccessToken(request);
		WeixinUserInfo userinfo = new WeixinUserInfo();
		// 用户同意授权
		if (!F6SystemUtils.isStrNull(code) && !"authdeny".equals(code)) {
			String openId = getOpenID(code);
			userinfo = WeiXinUtils.getUserDetail(weixintoken, openId);
		}
		return userinfo;

	}

	@RequestMapping(value = "payment", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public String payment(HttpServletRequest request) {
		return "weixinzhifu/";

	}

	@RequestMapping(value = "create", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String create(@RequestParam String access_token) throws IOException {
		if (F6SystemUtils.isStrNull(access_token)) {
			return "";
		} else {
			InputStream in = this.getClass().getClassLoader().getResourceAsStream("menu.json");
			return IOUtils.toString(in);
		}
	}

	@RequestMapping(value = SystemConstans.HOUTAI + "/rukou", method = RequestMethod.GET)
	public String login() throws IOException {
		return "ht/rukou";
	}

	@RequestMapping(value = SystemConstans.HOUTAI + "/dologin", method = RequestMethod.POST)
	@ResponseBody
	public Map dologin(@RequestBody Map param, HttpServletRequest request) throws IOException {
		String username = (String) param.get("username");
		String password = (String) param.get("password");
		String data = "0";
		if ("putongadmin".equals(username) && "bgt56yhn".equals(password)) {
			request.getSession().setAttribute(SystemConstans.CURRENT_USER, "putongadmin");

			data = "1";
		}

		return F6WebUtil.buildResponseMap(SystemConstans.RESPONSE_LABEL_SUCCESS, data, "ok");
	}

	@RequestMapping(value = "hi", method = RequestMethod.GET)
	@ResponseBody
	public String hi(HttpServletRequest request) {
		return "hi";
	}

	@RequestMapping(value = "imageupload", method = RequestMethod.POST)
	@ResponseBody
	public Map uploadImage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		MultipartFile file = F6WebUtil.saveFiles(request);
		logger.info("====" + file.getName());
		String filename = file.getOriginalFilename();
		String filepath = "";
		if (file != null) {
			byte[] filebyte = file.getBytes();

			logger.info("file==>" + filename);

			String path = "d:\\yangxi\\files";
			Long datatime = Calendar.getInstance().getTimeInMillis();
			filename = String.valueOf(datatime) + filename;
			filepath = path + "\\" + filename;

			logger.info("path==>" + filepath);
			File imagefile = new File(filepath);
			FileUtils.writeByteArrayToFile(imagefile, filebyte);
		}
		String contextpath = request.getContextPath();

		return F6WebUtil.buildResponseMap(SystemConstans.RESPONSE_LABEL_SUCCESS, contextpath + "/files/" + filename, "");

	}

	@RequestMapping(value = "/pay/openpay", method = RequestMethod.GET)
	public ModelAndView openpay() throws IOException {
		String redirecturl = WeiXinUtils.createOAuthURI(SystemConstans.WEIXIN_AUTH_REIDRECT_URL_TO_PAY);
		ModelAndView mv = new ModelAndView();
		mv.setViewName("weixinzhifu/payment");
		mv.addObject("redirecturl", redirecturl);
		return mv;
	}

	@RequestMapping(value = "/pay/topay", method = RequestMethod.GET)
	public ModelAndView topay(HttpServletRequest request) throws IOException {
		String code = request.getParameter("code");
		logger.info("=====code=========" + code);
		String qrcode = "";
		String imageqrcode = "";
		// 用户同意授权
		if (!F6SystemUtils.isStrNull(code) && !"authdeny".equals(code)) {
			WeiXinOauth2Token weixinOauth2Token = WeixinAuthUtil.getOauth2AccessToken(SystemConstans.APPID, SystemConstans.APPSECRET, code);
			String accessToken = weixinOauth2Token.getAccessToken();
			String openId = weixinOauth2Token.getOpenId();
		}
		ModelAndView mv = new ModelAndView();

		return mv;
	}

	@RequestMapping(value = "/pay/notify", method = RequestMethod.GET)
	public String pay() throws IOException {

		return "weixinzhifu/notfiy";
	}

	private UserVO getUserVOByOpenID(String openid) throws BusinessException {
		Map paramap = new HashMap<String, String>();
		paramap.put("idCode", openid);
		DBParameter dbparam = new DBParameter();
		dbparam.setAction("getUserByOpenID");
		dbparam.setModule("putong.User");
		dbparam.setParameter(paramap);

		Map map = commonservice.queryOne(dbparam);
		Set<String> keyset = map.keySet();
		for (Iterator<String> it = keyset.iterator(); it.hasNext();) {
			String key = it.next();
			logger.info("-&&--" + key + "---" + map.get(key));
		}

		UserVO vo = (UserVO) F6SystemUtils.parseMap2Obj(map, "com.f6.weixin.vo.UserVO");
		return vo;

	}
}
